import React, { Component } from 'react'
import {
  Text,
  View,
  Image,
  StyleSheet,
  ScrollView,
  Dimensions,
  Platform,
  PixelRatio,
  TextInput,
  FlatList,
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
  TouchableWithoutFeedback,
} from 'react-native'
import Immutable from 'immutable'
import Icon from 'react-native-vector-icons/Ionicons'
import StarRating from 'react-native-star-rating'
import RootView from '../component/RootView'
import Button from '../component/Button'
import Base from './Base'
import {
  NavigationActions,
  px2dp,
  createAction,
  imageServer,
  removeAsyncStorage,
} from '../utils'
import * as orderService from '../services/order'

const { width, height } = Dimensions.get('window')

const borderWidth = (Platform.OS === 'ios' ? 1.0 : 1.0) / PixelRatio.get()

class Comment extends Base {
  constructor(props) {
    super(props)
    this.state = {
      fetching: false,
      modalVisible: false,
      msg: '',
      starCount: {},
      orderId: 0,
      items: [],
    }
  }
  static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state
    return {
      title: '评价',
      headerBackTitle: null,

      headerRight: (
        <Button
          style={{ paddingHorizontal: 12 }}
          onPress={() => params.handleSubmit && params.handleSubmit()}
        >
          <Text style={{ fontSize: 14, color: '#000' }}>{'提交'}</Text>
        </Button>
      ),
      headerTitleStyle: {
        alignSelf: 'center',
      },
      headerStyle: {
        backgroundColor: '#fff',
        borderBottomWidth: 0,
        shadowColor: 'transparent',
        elevation: 1,
      },
    }
  }
  loadData(orderId) {
    this.setState({ fetching: true })
    orderService
      .detail({ orderId })
      .then(data => {
        this.setState({
          orderId,
          items: data.items,
          fetching: false,
        })
      })
      .catch(e => {
        this.checkError(e)
      })
  }

  onStarRatingPress = (rating, index) => {
    const data = this.state.starCount
    data[`star${index}`] = rating
    this.setState({
      starCount: data,
    })
  }
  submit = () => {
    const { fetching } = this.state
    if (fetching) {
      return
    }
    this.setState({ fetching: true })
    const array = []
    const { orderId } = this.state

    this.state.items.map((item, index) => {
      const productId = item.productId
      const rate = this.state.starCount[`star${index}`] || 5
      let content = this.state[`row${index}`]
      if (!content) {
        content = ''
      }
      array.push({
        productId,
        rate,
        content,
      })
    })
    const jsonData = JSON.stringify(array)

    orderService
      .comment({ orderId, jsonData })
      .then(data => {
        // 更新订单列表状态
        const { key } = this.props.navigation.state.params
        this.setParams(key, { reload: 1 })
        // 操作成功
        this.checkError({ msg: '操作成功' })
        setTimeout(() => {
          this.goBack()
        }, 50)
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  renderItem({ item, index }) {
    randerText = star => {
      if (star == 1) {
        return '非常差劲'
      }
      if (star == 2) {
        return '差劲'
      }
      if (star == 3) {
        return '一般'
      }
      if (star == 4) {
        return '不错喔'
      }
      if (star == 5) {
        return '非常好'
      }
    }

    return (
      <View key={index} style={{ flexDirection: 'row', marginTop: 20 }}>
        <Image
          style={{ width: 48, height: 48, marginRight: 15 }}
          source={{ uri: imageServer + item.imageSource }}
        />
        <View style={{ flex: 1 }}>
          <View style={{ width: 140 }}>
            <StarRating
              emptyStar={'ios-star-outline'}
              fullStar={'ios-star'}
              halfStar={'ios-star-half'}
              iconSet={'Ionicons'}
              starSize={24}
              maxStars={5}
              rating={this.state.starCount[`star${index}`] || 5}
              selectedStar={rating => this.onStarRatingPress(rating, index)}
              starColor={'#e23f3c'}
            />
          </View>
          <Text style={{ color: '#999' }}>
            {randerText(this.state.starCount[`star${index}`] || 5)}
          </Text>
          <TextInput
            style={{
              fontSize: 13,
            }}
            autoGrow
            autoFocus
            autoCapitalize="none"
            underlineColorAndroid="transparent"
            placeholder="说说它的优点和不足吧"
            placeholderTextColor="#999"
            multiline
            onChangeText={input => {
              this.setState({ [`row${index}`]: input })
            }}
          />
        </View>
      </View>
    )
  }
  shouldComponentUpdate = (nextProps, nextState) => true
  componentDidMount() {
    const { orderId } = this.props.navigation.state.params
    this.loadData(orderId)
    this.props.navigation.setParams({ handleSubmit: () => this.submit() })
  }
  render() {
    const { fetching, modalVisible, msg, items, starCount } = this.state
    return (
      <RootView fetching={fetching} style={styles.container}>
        <FlatList
          style={{ flex: 1 }}
          extraData={starCount}
          data={items}
          keyExtractor={(item, index) => index}
          renderItem={({ item, index }) => this.renderItem({ item, index })}
        />
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 16,
    backgroundColor: '#f6f6f6',
  },
})

export default Comment
